﻿using Abp.Dependency;
using Abp.Domain.Entities;
using Abp.EntityFramework;
using ARchGL.Platform.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace ARchGL.Platform.EntityFrameworkCore
{
    public class PluginEfCoreDbContextEntityFinder : IDbContextEntityFinder, ITransientDependency
    {
        private readonly IHostingEnvironment hostingEnvironment;
        public PluginEfCoreDbContextEntityFinder(IHostingEnvironment env)
        {
            hostingEnvironment = env;
        }

        public IEnumerable<EntityTypeInfo> GetEntityTypeInfos(Type dbContextType)
        {
            var p = dbContextType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var list = p
                   .Where(property => IsAssignableToGenericType(property.PropertyType, typeof(DbSet<>)))
                   .Where(property => IsAssignableToGenericType(property.PropertyType.GenericTypeArguments[0], typeof(IEntity<>)))
                   .Select(property => new EntityTypeInfo(property.PropertyType.GenericTypeArguments[0], property.DeclaringType))
                   .ToList();

            list.AddRange(GetPluginEntityTypeInfos(dbContextType));

            return list;
        }

        private List<string> FindPlugins()
        {
            try
            {
                var path = WebContentDirectoryFinder.GetContentRootFolder();
                path = Path.Combine(path, "wwwroot", "Plugins");
                return Directory.GetFiles(path, "*.dll").ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private IEnumerable<EntityTypeInfo> GetPluginEntityTypeInfos(Type dbContextType)
        {
            var list = new List<EntityTypeInfo>();

            if (dbContextType == typeof(HostDbContext))
            {
                return list;
            }

            foreach (string path in FindPlugins())
            {
                var p = Assembly.LoadFile(path).GetTypes();
                var allTypes = p
                    .Where(type => !string.IsNullOrWhiteSpace(type.Namespace))
                    //.Where(type => type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition().IsAssignableFrom(typeof(Entity<>))))
                    .Where(type => IsAssignableToGenericType(type, typeof(IEntity<>)))
                    .Select(type => new EntityTypeInfo(type, dbContextType));

                list.AddRange(allTypes);
            }

            return list;
        }

        private static bool IsAssignableToGenericType(Type givenType, Type genericType)
        {
            var givenTypeInfo = givenType.GetTypeInfo();

            if (givenTypeInfo.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
            {
                return true;
            }

            foreach (var interfaceType in givenType.GetInterfaces())
            {
                if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == genericType)
                {
                    return true;
                }
            }

            if (givenTypeInfo.BaseType == null)
            {
                return false;
            }

            return IsAssignableToGenericType(givenTypeInfo.BaseType, genericType);
        }
    }
}
